package com.campus.secondhand.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.secondhand.common.Result;
import com.campus.secondhand.entity.Product;
import com.campus.secondhand.entity.ShoppingCart;
import com.campus.secondhand.entity.User;
import com.campus.secondhand.entity.School;
import com.campus.secondhand.mapper.ProductMapper;
import com.campus.secondhand.mapper.ShoppingCartMapper;
import com.campus.secondhand.model.dto.ShoppingCartDTO;
import com.campus.secondhand.model.vo.PageVO;
import com.campus.secondhand.model.vo.ShoppingCartVO;
import com.campus.secondhand.service.ProductService;
import com.campus.secondhand.service.ShoppingCartService;
import com.campus.secondhand.service.UserService;
import com.campus.secondhand.service.SchoolService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 购物车服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart>
        implements ShoppingCartService {

    private final ProductMapper productMapper;
    private final UserService userService;
    private final ProductService productService;
    private final SchoolService schoolService;
    private final RedisTemplate<String, Object> redisTemplate;

    // Redis缓存键常量
    private static final String CACHE_CART_PREFIX = "cart:";
    private static final String CACHE_CART_LIST_PREFIX = "cart:list:";
    private static final long CACHE_CART_EXPIRE = 30; // 缓存过期时间，单位分钟

    /**
     * 获取购物车列表
     */
    @Override
    public Result<PageVO<ShoppingCartVO>> getCartList(Long userId, Integer pageNum, Integer pageSize) {
        // 校验用户是否存在
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 构建缓存键
        String cacheKey = CACHE_CART_LIST_PREFIX + userId + ":page:" + pageNum + ":size:" + pageSize;

        // 尝试从缓存获取
        Object cachedCart = redisTemplate.opsForValue().get(cacheKey);
        if (cachedCart != null) {
            log.info("从缓存获取购物车列表: {}", cacheKey);
            return Result.success((PageVO<ShoppingCartVO>) cachedCart, "获取成功(缓存)");
        }

        // 构建查询条件
        LambdaQueryWrapper<ShoppingCart> queryWrapper = Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, userId)
                .orderByDesc(ShoppingCart::getCreatedAt);

        // 执行分页查询
        IPage<ShoppingCart> page = new Page<>(pageNum, pageSize);
        page = page(page, queryWrapper);

        // 转换为VO
        List<ShoppingCartVO> voList = page.getRecords().stream().map(item -> {
            ShoppingCartVO vo = new ShoppingCartVO();
            BeanUtils.copyProperties(item, vo);

            // 设置用户名
            User itemUser = userService.getUserById(item.getUserId());
            if (itemUser != null) {
                vo.setUserName(itemUser.getUsername());
            }

            // 获取商品信息
            Product product = productMapper.selectById(item.getProductId());
            if (product != null) {
                vo.setProductName(product.getName());
                vo.setPrice(product.getPrice());
                vo.setProductDescription(product.getDescription());

                // 设置学校和位置信息
                if (product.getSchoolId() != null) {
                    School school = schoolService.getById(product.getSchoolId());
                    vo.setSchoolName(school != null ? school.getName() : "");
                }
                vo.setLocationDescription(product.getLocationDescription());

                // 获取商品图片(使用ProductService的商品详情方法)
                try {
                    vo.setProductImage(productService.getProductDetail(product.getId(), null)
                            .getData()
                            .getImageUrls()
                            .get(0));
                } catch (Exception e) {
                    log.error("获取商品图片失败: {}", e.getMessage());
                    vo.setProductImage("");
                }
            }

            return vo;
        }).collect(Collectors.toList());

        // 构建分页结果
        PageVO<ShoppingCartVO> pageVO = new PageVO<>(voList, page.getTotal());

        // 保存到缓存
        redisTemplate.opsForValue().set(cacheKey, pageVO, CACHE_CART_EXPIRE, TimeUnit.MINUTES);

        return Result.success(pageVO);
    }

    /**
     * 添加商品到购物车
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<ShoppingCartVO> addToCart(ShoppingCartDTO shoppingCartDTO) {
        // 校验用户是否存在
        User user = userService.getUserById(shoppingCartDTO.getUserId());
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 校验商品是否存在
        Product product = productMapper.selectById(shoppingCartDTO.getProductId());
        if (product == null) {
            return Result.error(404, "商品不存在");
        }

        // 检查商品是否已在购物车中
        LambdaQueryWrapper<ShoppingCart> queryWrapper = Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, shoppingCartDTO.getUserId())
                .eq(ShoppingCart::getProductId, shoppingCartDTO.getProductId());

        ShoppingCart existingItem = getOne(queryWrapper);
        if (existingItem != null) {
            // 已存在，直接返回
            ShoppingCartVO vo = convertToVO(existingItem, product);
            return Result.success(vo, "商品已在购物车中");
        }

        // 创建购物车项
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(shoppingCartDTO.getUserId());
        shoppingCart.setProductId(shoppingCartDTO.getProductId());
        shoppingCart.setCreatedAt(LocalDateTime.now());

        // 保存购物车项
        save(shoppingCart);

        // 清除购物车缓存
        clearCartCache(shoppingCartDTO.getUserId());

        // 转换为VO并返回
        ShoppingCartVO vo = convertToVO(shoppingCart, product);
        return Result.success(vo, "添加成功");
    }

    /**
     * 从购物车移除商品
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> removeFromCart(Long userId, Long id) {
        // 校验用户是否存在
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 查询购物车项
        ShoppingCart shoppingCart = getById(id);
        if (shoppingCart == null) {
            return Result.error(404, "购物车项不存在");
        }

        // 验证用户权限
        if (!shoppingCart.getUserId().equals(userId)) {
            return Result.error(403, "无权限操作他人购物车");
        }

        // 删除购物车项
        boolean success = removeById(id);
        if (!success) {
            return Result.error("删除失败");
        }

        // 清除购物车缓存
        clearCartCache(userId);

        return Result.success(null, "删除成功");
    }

    /**
     * 清空购物车
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> clearCart(Long userId) {
        // 校验用户是否存在
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 删除用户的所有购物车项
        LambdaQueryWrapper<ShoppingCart> queryWrapper = Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, userId);
        boolean success = remove(queryWrapper);

        if (success) {
            // 清除购物车缓存
            clearCartCache(userId);
            return Result.success(null, "清空购物车成功");
        } else {
            return Result.error("清空购物车失败");
        }
    }

    /**
     * 将购物车实体转换为VO
     */
    private ShoppingCartVO convertToVO(ShoppingCart shoppingCart, Product product) {
        ShoppingCartVO vo = new ShoppingCartVO();
        BeanUtils.copyProperties(shoppingCart, vo);

        // 设置商品信息
        if (product != null) {
            vo.setProductName(product.getName());
            vo.setPrice(product.getPrice());
            vo.setProductDescription(product.getDescription());

            // 设置学校和位置信息
            if (product.getSchoolId() != null) {
                School school = schoolService.getById(product.getSchoolId());
                vo.setSchoolName(school != null ? school.getName() : "");
            }
            vo.setLocationDescription(product.getLocationDescription());

            // 获取商品图片
            try {
                vo.setProductImage(productService.getProductDetail(product.getId(), null)
                        .getData()
                        .getImageUrls()
                        .get(0));
            } catch (Exception e) {
                log.error("获取商品图片失败: {}", e.getMessage());
                vo.setProductImage("");
            }
        }

        return vo;
    }

    /**
     * 清除用户购物车缓存
     */
    private void clearCartCache(Long userId) {
        if (userId == null) {
            return;
        }

        log.info("清除用户购物车缓存: {}", userId);
        String pattern = CACHE_CART_LIST_PREFIX + userId + "*";
        redisTemplate.keys(pattern).forEach(key -> {
            redisTemplate.delete(key);
        });
    }
}